package com.yyfax.pay.order.data.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.yyfax.commons.lang.DateUtil;
import com.yyfax.framework.exception.YYException;
import com.yyfax.framework.service.CacheService;
import com.yyfax.framework.service.impl.BaseServiceImpl;
import com.yyfax.pay.common.constants.PayConstants;
import com.yyfax.pay.common.enums.OrderStateEnum;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.common.enums.PayTypeEnum;
import com.yyfax.pay.common.util.CommonIdUtils;
import com.yyfax.pay.order.data.dao.PayoutOrderDao;
import com.yyfax.pay.order.data.service.PayoutOrderLogService;
import com.yyfax.pay.order.data.service.PayoutOrderService;
import com.yyfax.pay.order.model.po.PayoutOrderLogPO;
import com.yyfax.pay.order.model.po.PayoutOrderPO;
import com.yyfax.pay.order.model.vo.PayBusiIdVO;
import com.yyfax.pay.order.model.vo.PayoutOrderVO;

/**
 * 代付订单服务实现
 *
 * @author buyi
 * @date 2017-04-12 11:09:15
 * @since 1.0.0
 */
@Service
public class PayoutOrderServiceImpl extends BaseServiceImpl implements PayoutOrderService {
	private Logger logger = LoggerFactory.getLogger(getClass());

	private final String PAYOUT_ORDER_ID_PREFIX = "O";
	private final String PAYOUT_ORDER_ID_CONCAT = "_";

	@Autowired
	private PayoutOrderDao payoutOrderDao;

	@Autowired
	private PayoutOrderLogService payoutOrderLogService;

	@Autowired
	private PayConstants payConstants;

	public PayoutOrderServiceImpl(@Qualifier("payCacheService") CacheService cacheService) {
		super(cacheService);
	}

	@Override
	public PayBusiIdVO resolverPayoutOrderId(String payoutOrderId) throws Exception {
		if (StringUtils.isBlank(payoutOrderId)) {
			return null;
		}

		String[] split = payoutOrderId.split(PAYOUT_ORDER_ID_CONCAT);

		if (split.length < 3) {
			throw new YYException(PayRspCodeEnum.COMMON_ERROR_PARAMETER_INVALID, "参数payOrderId异常,封装规则PREFIX_MERCHANTCODE_ORDERID");
		}

		return new PayBusiIdVO(split[1], split[2]);
	}

	/**
	 * 获取业务主键
	 * 
	 * @author buyi
	 * @date 2017-04-15 14:01:56
	 * @since v1.0.0
	 * @param merchantCode
	 * @param orderId
	 * @return
	 */
	private String getPayoutOrderId(String merchantCode, String orderId) {
		return PAYOUT_ORDER_ID_PREFIX.concat(PAYOUT_ORDER_ID_CONCAT).concat(merchantCode).concat(PAYOUT_ORDER_ID_CONCAT).concat(orderId);
	}

	@Override
	public PayoutOrderPO queryByPayoutOrderId(String payoutOrderId) {
		return payoutOrderDao.selectByPayoutOrderId(payoutOrderId);
	}

	@Override
	public PayoutOrderPO queryByIdAndMerchantCode(int id, String merchantCode) throws Exception {
		if (id <= 0 && StringUtils.isBlank(merchantCode)) {
			logger.debug("参数 'id' 不能为0，且 'merchantCode' 不能为空 ");
			return null;
		}

		return payoutOrderDao.selectByIdAndMerchantCode(id, merchantCode);
	}

	@Override
	public PayoutOrderPO queryByOrderIdAndMerchantCode(String orderId, String merchantCode) throws Exception {
		if (StringUtils.isBlank(orderId) && StringUtils.isBlank(merchantCode)) {
			logger.debug("参数 orderId/merchantCode 为空 ");
			return null;
		}

		return payoutOrderDao.selectByOrderIdAndMerchantCode(orderId, merchantCode);
	}

	@Override
	public PayoutOrderVO queryPayoutOrderVOByOrderId(String orderId, String merchantCode) throws Exception {
		PayoutOrderPO payoutOrderPO = queryByOrderIdAndMerchantCode(orderId, merchantCode);
		if (payoutOrderPO == null) {
			return null;
		}

		return trasformPayoutOrderVO(payoutOrderPO);
	}

	@Override
	public List<PayoutOrderVO> queryPayoutOrderVoList(String merchantCode, String payoutBatchOrderId) {
		if (StringUtils.isBlank(merchantCode) && StringUtils.isBlank(payoutBatchOrderId)) {
			return null;
		}

		List<PayoutOrderVO> payoutOrderVOs = new ArrayList<PayoutOrderVO>();

		List<PayoutOrderPO> payoutOrderPOs = payoutOrderDao.selectByMerchantCodeAndPayoutBatchOrderId(merchantCode, payoutBatchOrderId);
		if (payoutOrderPOs != null) {
			for (PayoutOrderPO payoutOrderPO : payoutOrderPOs) {
				payoutOrderVOs.add(trasformPayoutOrderVO(payoutOrderPO));
			}
		}

		return payoutOrderVOs;
	}

	/**
	 * 持久化转换成快照类
	 * 
	 * @author buyi
	 * @date 2017-04-20 11:33:13
	 * @since v1.0.0
	 * @param payoutOrderPO
	 * @return
	 */
	private PayoutOrderVO trasformPayoutOrderVO(PayoutOrderPO payoutOrderPO) {
		if (payoutOrderPO == null) {
			return null;
		}

		PayoutOrderVO payoutOrderVO = new PayoutOrderVO();
		payoutOrderVO.setPayoutOrderPO(payoutOrderPO);

		List<PayoutOrderLogPO> payoutOrderLogPOs = payoutOrderLogService.queryListByPayoutOrderId(payoutOrderPO.getPayoutOrderId(),
				payoutOrderPO.getMerchantCode());
		payoutOrderVO.setOrderLogPOs(payoutOrderLogPOs);

		// payoutOrderVO.setClose(false);

		// 迭代判断订单关闭，和结果代码
		// if (payoutOrderLogPOs != null) {
		// for (PayoutOrderLogPO payoutOrderLogPO : payoutOrderLogPOs) {
		//
		// // if (YesNoEnum.YES.isValue(payoutOrderLogPO.getClosed())) {
		// // payoutOrderVO.setClose(true);
		// // }
		//
		// if (StringUtils.isBlank(payoutOrderVO.getSerialNo())
		// && StringUtils.isNotBlank(payoutOrderLogPO.getSerialNo())) { //
		// 设置业务流水号
		// payoutOrderVO.setSerialNo(payoutOrderLogPO.getSerialNo());
		// }
		//
		// }
		// }

		// 判断订单是否失效
		// if (DateUtil.str2DateTime(payoutOrderVO.getExpireTime()).getTime() <=
		// System.currentTimeMillis()) {
		// payoutOrderVO.setExpire(true);
		// }

		return payoutOrderVO;
	}

	@Override
	public String saveAndReturnBusiKey(PayoutOrderPO po) throws Exception {
		if (po == null) {
			logger.debug("参数po为空，返回-1");
			return null;
		}

		// // 判断重复下单
		// PayoutOrderPO orderPO =
		// queryByOrderIdAndMerchantCode(po.getOrderId(), po.getMerchantCode());
		// if (orderPO != null) {
		// throw new YYException(PayRspCodeEnum.PAY_CODE_ORDER_DUPLICATE,
		// "order：" + po.getOrderId() + ",merchantCode:" + po.getMerchantCode()
		// + "已经存在");
		// }

		// 生成业务主键
		String busiId = CommonIdUtils.generateId(PayTypeEnum.PAY_OUT, po.getMerchantCode(), po.getOrderId());

		if (StringUtils.isBlank(po.getExpireTime())) { // 如果没有传订单过期时间，则默认生成过期时间
			long expireTime = DateUtil.str2DateTime(po.getOrderTime()).getTime() + payConstants.getDefaultExpireTime();
			po.setExpireTime(DateUtil.milli2str(expireTime));
		}

		po.setPayoutOrderId(busiId);
		po.setCreateTime(DateUtil.getCurrentDateTime());
		int id = payoutOrderDao.insert(po);
		po.setId(id);

		return busiId;
	}

	@Override
	public int save(PayoutOrderPO po) {
		if (po == null) {
			logger.debug("参数po为空，返回-1");
			return -1;
		}

		int id = payoutOrderDao.insert(po);
		po.setId(id);

		return 1;
	}

	@Override
	public void modify(PayoutOrderPO payoutOrderPO) throws Exception {
		if (payoutOrderPO == null || payoutOrderPO.getId() == null) {
			return;
		}

		payoutOrderDao.update(payoutOrderPO);
	}

	@Override
	public int updateState(String payoutOrderId, OrderStateEnum origState, OrderStateEnum destState, int rspCode, String rspMsg) {
		return payoutOrderDao.updateState(payoutOrderId, origState.getValue(), destState.getValue(), rspCode, rspMsg);
	}

	@Override
	public int updateStateByPayoutOrderId(String payoutOrderId, String state, Integer rspCode, String rspMsg) {
		return payoutOrderDao.updateStateByPayoutOrderId(payoutOrderId, state, rspCode, rspMsg);
	}

	@Override
	public int updateRefundState(String payoutOrderId, OrderStateEnum fail, int rspCode, String rspDesc, String origIsRefund, String destIsRefund) {
		return payoutOrderDao.updateRefundState(payoutOrderId, fail.getValue(), rspCode, rspDesc, origIsRefund, destIsRefund);
	}
}
